package com.example.springbootuploadanddownload.controller;


import jakarta.servlet.ServletException;
import jakarta.servlet.ServletInputStream;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.Part;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
/**
 * 上传到指定路径下
 * */
@RestController
@Slf4j
@RequestMapping("/path")
public class UploadController {

    @RequestMapping(value = "/upload2", method = RequestMethod.POST)
    public String upload2(HttpServletRequest request) throws IOException {
        ServletInputStream inputStream = null;
        FileOutputStream fileOutputStream = null;
        try {
            inputStream = request.getInputStream();
            //要有名称，因为前端提交的是二进制
            fileOutputStream = new FileOutputStream(new File("D:\\Users\\Mixi\\IdeaProjects\\springboot-uploadanddownload\\src\\main\\resources\\static\\20200902092849278.png"));

            int len;
            byte[] bytes = new byte[1024];
            while ((len = inputStream.read(bytes)) != -1) {
                fileOutputStream.write(bytes, 0, len);
            }
        } catch (IOException e) {
            e.printStackTrace();
            return "上传失败";
        } finally {
            if (fileOutputStream != null) {
                fileOutputStream.close();
            }
            if (inputStream != null) {
                inputStream.close();
            }
        }
        return "上传成功";
    }

    private BufferedOutputStream bufferedOutputStream = null;

    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    public String readFile(HttpServletRequest request, @RequestParam("name") String name, @RequestPart("file1") MultipartFile file3, @RequestPart("photo") MultipartFile[] photo) throws IOException, ServletException {

        String path = "D:\\Users\\Mixi\\IdeaProjects\\springboot-uploadanddownload\\src\\main\\resources\\static\\";

        System.out.println(name);
        System.out.println(file3);
        System.out.println(photo);

        //前端传递多个file
        for (MultipartFile multipartFile : photo) {
            fileUtil(multipartFile, String.valueOf(path));
        }

//        第一种 ： 使用 MultipartFile 封装好的 transferTo() 方法保存文件
//        photo.transferTo(new File(path+photo.getOriginalFilename()));

//        第二种 ：  使用 MultipartFile 字节流保存文件
//         fileUtil(file3, String.valueOf(path));

//		第三种 ：  使用 Part 接收文件字节流
//        Part file2 = request.getPart("file2");
//        file2.write(path + file2.getSubmittedFileName());

        // request.getParts() 获取的是全部参数（name,age,file1,file2），包括文件参数和非文件参数
        /*for (Part part : request.getParts()) {
            // 获取文件类型
            String contentType = part.getContentType();
            // 获取文件大小
            long size = part.getSize();
            // 获取文件名
            String submittedFileName = part.getSubmittedFileName();
            // 获取参数名 （name,age,file1,file2）
            String name1 = part.getName();

            if (part.getContentType() != null) {
                //如果是文件会进行写入
                part.write(path + part.getSubmittedFileName());
            } else {
                // 如果是参数会获取参数
                // 可以获取文本参数值,文本参数 part.getContentType() 为 null
                request.getParameter(part.getName());
            }
        }*/
        return "success";
    }

    public String fileUtil(MultipartFile file, String path) {

        if (!file.isEmpty()) {
            try {
                byte[] bytes = file.getBytes();
                bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(
                        new File(path + file.getOriginalFilename())));
                bufferedOutputStream.write(bytes);
                bufferedOutputStream.close();
                return file.getOriginalFilename() + "success upload";
            } catch (Exception e) {
                return file.getOriginalFilename() + "failed to upload ---> " + e;
            }
        } else {
            return file.getOriginalFilename() + "You failed to upload file was empty.";
        }
    }


}
